############################################################################
# A sample program to create a single-track MIDI file, add a note,
# and write to disk.
############################################################################

#Import the library
from midiutil.MidiFile import MIDIFile
import random
# Create the MIDIFile Object
MyMIDI = MIDIFile(1)

# Add track name and tempo. The first argument to addTrackName and
# addTempo is the time to write the event.
track = 0
time = 0
MyMIDI.addTrackName(track,time,"Piano")
MyMIDI.addTempo(track,time, 120)

# Add a note. addNote expects the following information:
channel = 0
duration = 1
volume = 100
notes=8
i=0
scale=[0, 2, 4, 5, 7, 9, 11]
fullScale=[]
for octave in range(3,9):
    for note in scale:
        fullScale.append(note+12*octave)


print(fullScale)
print(len(fullScale))

# Now add the note.
prevType='jump'
prev=6
types=['jump', 'jump']
def jump(prev, prevType):
    if prev<=len(scale)/2:
        num=random.randint(prev+3, len(scale)-1)
    else: 
        num=random.randint(0, prev-3)
    return num
    
    
def step(prev, prevType):
    if prevType=="jumpDown" or prev<4:
        num=random.randint(prev, prev+3)
    elif prevType=="jumpUp" or prev>len(scale)-4:
        num=random.randint(prev-3, prev)
    else:
        num=random.randint(prev-3, prev+3)
        prevType="step"
    return num

for i in range(40):
    percent=random.randint(0,100)
    if types[-1].count("jump")==1 or types[-2].count("jump")==1:
        if percent>=95:
            num=jump(prev, prevType)
            if prev<num:
                prevType="jumpUp"
            else: prevType="jumpDown"
        else:
            num=step(prev, prevType)
            prevType="step"
    else:
        if percent>=70:
            num=jump(prev, prevType)
            if prev<num:
                prevType="jumpUp"
            else: prevType="jumpDown"
        else:
            num=step(prev, prevType)
            prevType="step"
    #
    print(prevType)
    types.append(prevType)
    #num=random.randint(2,len(fullScale)-2)
    print(num)
    triad=[[0,0,-2,-4], [0,-2,0,-5], [0,-5,-3,0]]
    choice=random.randint(0,2)
    triadUsed=triad[choice]
    MyMIDI.addNote(track,channel+0,72+scale[num+triadUsed[0]],i,duration,volume)
    MyMIDI.addNote(track,channel+1,60+scale[num+triadUsed[1]],i,duration,volume)
    MyMIDI.addNote(track,channel+2,48+scale[num+triadUsed[2]],i,duration,volume)
    MyMIDI.addNote(track,channel+3,36+scale[num+triadUsed[3]],i,duration,volume)
    prev=num

        

print(types)
# And write it to disk.
binfile = open("output.mid", 'wb')
MyMIDI.writeFile(binfile)
binfile.close()

